<template>
  <view class="container">
    <!-- 顶部导航栏 -->
<!--    <view class="nav-bar">
      <view class="left">
        <u-icon name="arrow-left" size="32" color="#333" @click="goBack"></u-icon>
      </view>
      <view class="title">个人信息</view>
      <view class="right"></view>
    </view> -->

    <!-- 内容区域 -->
		
    <view class="content">
      <!-- 姓名 -->
      <view class="info-item" @click="openEditPopup({
		  type: 'input',
		  title: '姓名',
		  placeholder: '请输入姓名',
		  value: userInfo.nickName,
		  field: 'nickName'
		})">
        <text class="label">姓名</text>
        <view class="value">
          <text>{{ userInfo.nickName || '请输入' }}</text>
          <u-icon name="arrow-right" size="28" color="#999"></u-icon>
        </view>
      </view>


      <!-- 性别 -->
      <view class="info-item" @click="editGender">
        <text class="label">性别</text>
        <view class="value">
          <text>{{ genderText }}</text>
          <u-icon name="arrow-right" size="28" color="#999"></u-icon>
        </view>
      </view>

      <!-- 年龄 -->
      <view class="info-item" @click="editAge">
        <text class="label">年龄</text>
        <view class="value">
          <text>{{ userInfo.age ? currentYear - userInfo.age + '岁' : '请选择出生年份' }}</text>
          <u-icon name="arrow-right" size="28" color="#999"></u-icon>
        </view>
      </view>

      <!-- 住院号 -->
<!--      <view class="info-item" @click="openEditPopup({
			type: 'input',
			title: '住院号',
			placeholder: '请输入住院号',
			value: userInfo.hospitalId,
			field: 'hospitalId'
        })">
        <text class="label">住院号</text>
        <view class="value">
          <text>{{ userInfo.hospitalId || '请输入' }}</text>
          <u-icon name="arrow-right" size="28" color="#999"></u-icon>
        </view>
      </view> -->

      <!-- 脑卒中病史 -->
	  <view class="info-item" @click="openEditPopup({
				type: 'checkbox',
				title: '脑卒中病史',
				value: userInfo.strokeDiseaseHistory,
				options: this.strokeDiseaseOptions,
				field: 'strokeDiseaseHistory'
			  })">
        <text class="label">卒中类型</text>
        <view class="value">
          <text>{{ strokeHistoryText }}</text>
          <u-icon name="arrow-right" size="28" color="#999"></u-icon>
        </view>
      </view>

      <!-- 脑卒中病史次数 -->
      <view class="info-item" @click="openEditPopup({
			type: 'input',
			title: '脑卒中病史次数',
			placeholder: '请输入次数',
			value: userInfo.diseaseTimes,
			field: 'diseaseTimes'
		  })">
        <text class="label">脑卒中病史次数</text>
        <view class="value">
          <text>{{ userInfo.diseaseTimes || '请输入' }}</text>
          <u-icon name="arrow-right" size="28" color="#999"></u-icon>
        </view>
      </view>

      <!-- 其他疾病 -->
	  <view class="info-item" @click="openEditPopup({
					type: 'checkbox',
					title: '其他疾病',
					value: userInfo.otherDisease,
					options: this.otherDiseaseOptions,
					field: 'otherDisease'
				  })">
        <text class="label">其他疾病</text>
        <view class="value">
          <text>{{ otherDiseaseText }}</text>
          <u-icon name="arrow-right" size="28" color="#999"></u-icon>
        </view>
      </view>

      <!-- 现居住地南北 -->
      <view class="info-item" @click="editResidence1">
        <text class="label">现居住地（南北）</text>
        <view class="value">
          <text>{{ residenceText1 }}</text>
          <u-icon name="arrow-right" size="28" color="#999"></u-icon>
        </view>
      </view>
	  
	  <!-- 现居住地城市农村 -->
	  <view class="info-item" @click="editResidence2">
	    <text class="label">现居住地（城市农村）</text>
	    <view class="value">
	      <text>{{ residenceText2 }}</text>
	      <u-icon name="arrow-right" size="28" color="#999"></u-icon>
	    </view>
	  </view>

      <!-- 电话 -->
	  <view class="info-item" @click="openEditPopup({
				type: 'input',
				title: '电话',
				placeholder: '请输入电话号码',
				value: userInfo.phonenumber,
				field: 'phonenumber'
			  })">
        <text class="label">电话</text>
        <view class="value">
          <text>{{ userInfo.phonenumber || '请输入' }}</text>
          <u-icon name="arrow-right" size="28" color="#999"></u-icon>
        </view>
      </view>
    </view>

    <!-- 保存按钮 -->
    <view class="save-btn" @click="saveInfo">
      <text>保存</text>
    </view>

	<!-- 通用弹窗 -->
	<uni-popup ref="editPopup" type="dialog">
	  <view class="custom-modal">
		<view class="modal-title">{{ popupTitle }}</view>

		<!-- 文本输入模式 -->
		<view v-if="popupType === 'input'">
		  <input class="modal-input" type="number" v-model="tempInput" :placeholder="popupPlaceholder" />
		</view>

		<!-- 多选模式 -->
		<view v-if="popupType === 'checkbox'" class="checkbox-list">
<!-- 		  <u-checkbox-group v-model="checkedItems">
			<label v-for="(item, index) in popupOptions" :key="index" class="checkbox-item">
			  <u-checkbox :value="item" />
			  <text>{{ item }}</text>
			</label>
		  </u-checkbox-group> -->
		  <checkbox-group @change="onCheckboxGroupChange">
		    <label v-for="(item, index) in popupOptions" :key="index" class="checkbox-item">
		      <checkbox :value="item" :checked="checkedItems.includes(item)" />
		      <text>{{ item }}</text>
		    </label>
		  </checkbox-group>

<!-- 		  <label v-for="(item, index) in popupOptions" :key="index" class="checkbox-item">
			<checkbox :checked="checkedItems.includes(item)" @change="toggleCheckbox(item)" />
			<text>{{ item }}</text>
		  </label> -->


		  <!-- “其他”输入 -->
<!-- 		  <view class="other-input">
			<checkbox :checked="checkedItems.includes(otherValue)" @change="toggleOtherChecked" />
			<input v-model="otherValue" placeholder="如果有，请输入其他疾病" @input="onOtherInput" />
		  </view> -->
		</view>

		<!-- 操作按钮 -->
		<view class="modal-actions">
		  <button @click="cancelEdit">取消</button>
		  <button @click="confirmEdit">确定</button>
		</view>
	  </view>
	</uni-popup>
	
      

  </view>
</template>

<script>
import { getStrokeUserInfo,updateUserInfo } from '@/common/api.js';

export default {
  data() {
    return {
    popupType: '', // 或 'checkbox'
    popupTitle: '',
    popupPlaceholder: '',
    popupOptions: [], // 多选列表
    checkedItems: [], // 勾选结果
    otherValue: '', // “其他”输入框临时值
    tempInput: '', // 普通输入框临时值
    currentEditField: '', // 正在编辑的字段标识
      userInfo: {},
      popupVisible: false,
      popupInput: '',
      currentField: '',

      // 多选支持
      strokeDiseaseOptions: ['缺血性脑卒中(脑梗死)', '出血性脑卒中(脑出血)','短暂性脑缺血发作(TIA)','其他'],
      otherDiseaseOptions: ['糖尿病', '高血压', '高血脂', '房颤或瓣膜性心脏病', '脑卒中家族史','其他'],

      // 临时字段
      tempMultiSelect: [],
      tempOtherInput: '',
      multiSelectMode: '', // stroke 或 other
      multiSelectVisible: false,
	  
	  currentYear: new Date().getFullYear()
    };
  },
  computed: {
    genderText() {
      if (this.userInfo.sex === '0') return '男';
      if (this.userInfo.sex === '1') return '女';
      return '请选择';
    },
    strokeHistoryText() {
      return this.userInfo.strokeDiseaseHistory?.length
        ? this.userInfo.strokeDiseaseHistory
        : '请选择';
    },
    otherDiseaseText() {
      return this.userInfo.otherDisease?.length
        ? this.userInfo.otherDisease
        : '请选择';
    },
    residenceText1() {
      if (this.userInfo.residentNorthSouth === '0') return '北方';
      if (this.userInfo.residentNorthSouth === '1') return '南方';
      return '请选择';
    },
	residenceText2() {
	  if (this.userInfo.residentCityCountry === '0') return '城市';
	  if (this.userInfo.residentCityCountry === '1') return '农村';
	  return '请选择';
	}
  },
  onShow() {
    this.loadUserInfo();
  },
  methods: {
    async loadUserInfo() {
      try {
        const res = await getStrokeUserInfo();
        if (res && res.code === 200) {
          this.userInfo = res.data;
        }
      } catch (err) {
        console.error('加载用户信息失败', err);
      }
    },
    goBack() {
      uni.navigateBack();
    },
	/** 打开弹窗：通用调用方法 */
	  openEditPopup({ type, title, placeholder, value, options, field }) {
		this.popupType = type
		this.popupTitle = title
		this.popupPlaceholder = placeholder || ''
		this.currentEditField = field

		if (type === 'input') {
		  this.tempInput = value || ''
		} else if (type === 'checkbox') {
		  // 将字符串值拆为数组
		  // this.checkedItems = typeof value === 'string' ? value.split('、') : []
		  this.checkedItems = typeof value === 'string' ? value.split('、') : (Array.isArray(value) ? value : []);
		  this.popupOptions = options || []
		  // 自动识别“其他”选项
		  //this.otherValue = this.checkedItems.find(v => !this.popupOptions.includes(v)) || ''
		}

		this.$refs.editPopup.open()
	  },
	/** 确定按钮 */
	  confirmEdit() {
		  const field = this.currentEditField;
		  const value = this.tempInput?.trim?.();
		if (this.popupType === 'input') {
			// 字段验证
			if (field === 'strokeTime') {
			  const number = parseInt(value);
			  if (!/^\d+$/.test(value)) {
				uni.showToast({ title: '请输入正确的次数（正整数）', icon: 'none' });
				return;
			  }
			}
		
			if (field === 'phonenumber') {
			  if (!/^1[3-9]\d{9}$/.test(value)) {
				uni.showToast({ title: '请输入有效的手机号', icon: 'none' });
				return;
			  }
			}
		  this.userInfo[field] = value;
		} else if (this.popupType === 'checkbox') {
/* 		  const final = [...this.checkedItems];
		  if (this.otherValue && !this.popupOptions.includes(this.otherValue)) {
			final.push(this.otherValue)
		  }
		  this.userInfo[field] = final.join('、'); */
		  const final = [...this.checkedItems];
		  this.userInfo[field] = final.length === 1 ? final[0] : final.join('、');
		  console.log('解析后 checkedItems:', this.checkedItems);
		}
		this.$refs.editPopup.close()
	  },

	  cancelEdit() {
		this.$refs.editPopup.close()
	  },
	  
	  onCheckboxGroupChange(e) {
	    this.checkedItems = e.detail.value;
	  },


	  /** 选中/取消复选框 */
/* 	  toggleCheckbox(item) {
		const idx = this.checkedItems.indexOf(item)
		if (idx === -1) {
		  this.checkedItems.push(item)
		} else {
		  this.checkedItems.splice(idx, 1)
		}
	  }, */

/* 	  toggleOtherChecked(e) {
		const isChecked = e.detail.value.length > 0
		if (!isChecked) {
		  this.checkedItems = this.checkedItems.filter(item => item !== this.otherValue)
		} else if (this.otherValue && !this.checkedItems.includes(this.otherValue)) {
		  this.checkedItems.push(this.otherValue)
		}
	  }, */

/* 	  onOtherInput(e) {
		const oldOther = this.otherValue
		this.otherValue = e.detail.value

		// 替换 checkedItems 中的旧值
		const idx = this.checkedItems.indexOf(oldOther)
		if (idx !== -1) {
		  this.checkedItems.splice(idx, 1, this.otherValue)
		}
	  }, */
    confirmPopup() {
      this.userInfo[this.currentField] = this.popupInput;
      this.popupVisible = false;
    },
    cancelPopup() {
      this.popupVisible = false;
    },
    editGender() {
      uni.showActionSheet({
        itemList: ['男', '女'],
        success: res => {
          this.userInfo.sex = res.tapIndex === 2 ? '0' : '1';
        }
      });
    },
    editAge() {
      const currentYear = new Date().getFullYear();
      const years = [];
      for (let i = currentYear; i >= 1900; i--) years.push(i.toString());

      uni.showActionSheet({
        itemList: years,
        success: res => {
          const birthYear = parseInt(years[res.tapIndex]);
          this.userInfo.age = birthYear;
        }
      });
    },
    editResidence1() {
      uni.showActionSheet({
        itemList: ['北方', '南方'],
        success: res => {
          this.userInfo.residentNorthSouth = res.tapIndex.toString();
        }
      });
    },
	editResidence2() {
	  uni.showActionSheet({
	    itemList: ['城市', '农村'],
	    success: res => {
	      this.userInfo.residentCityCountry = res.tapIndex.toString();
	    }
	  });
	},
    getOtherValue(list) {
      const other = list.find(i => !this.strokeDiseaseOptions.includes(i) && !this.otherDiseaseOptions.includes(i));
      return other || '';
    },
    toggleOption(option) {
      const index = this.tempMultiSelect.indexOf(option);
      if (index === -1) {
        this.tempMultiSelect.push(option);
      } else {
        this.tempMultiSelect.splice(index, 1);
      }
    },
    confirmMultiSelect() {
      const finalList = this.tempMultiSelect.filter(item => item !== '其他');
      if (this.tempOtherInput) {
        finalList.push(this.tempOtherInput);
      }
      if (this.multiSelectMode === 'stroke') {
        this.userInfo.strokeHistory = finalList;
      } else if (this.multiSelectMode === 'other') {
        this.userInfo.otherDisease = finalList;
      }
      this.multiSelectVisible = false;
    },
    async saveInfo() {
		console.log(this.userInfo);
      try {
        const res = await updateUserInfo(this.userInfo);
        if (res.code === 200) {
          uni.showToast({ title: '保存成功', icon: 'success' });
		  setTimeout(() => {
		  	uni.navigateBack();
		  }, 1500);
        } else {
          uni.showToast({ title: '保存失败', icon: 'none' });
        }
      } catch (err) {
        console.error('提交失败', err);
        uni.showToast({ title: '提交失败', icon: 'none' });
      }
    }
  }
};
</script>

<style lang="scss">
	.container {
		min-height: 100vh;
		background-color: #F7F7FA;
		
		.nav-bar {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 30rpx;
			background-color: #fff;
			
			.title {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
			}
		}
		
		.content {
			padding: 30rpx;
			padding-bottom: 120rpx;
			
			.section-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				margin: 30rpx 0;
			}
			
			.info-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 30rpx;
				background-color: #fff;
				border-radius: 16rpx;
				margin-bottom: 20rpx;
				
				.label {
					font-size: 28rpx;
					color: #333;
				}
				
				.value {
					display: flex;
					align-items: center;
					
					text {
						font-size: 28rpx;
						color: #666;
						margin-right: 10rpx;
					}
					
					input {
						text-align: right;
						font-size: 28rpx;
						color: #666;
					}
					
					&.avatar {
						image {
							width: 80rpx;
							height: 80rpx;
							border-radius: 40rpx;
							margin-right: 10rpx;
						}
					}
				}
			}
		}
		
		.save-btn {
			position: fixed;
			bottom: 40rpx;
			left: 30rpx;
			right: 30rpx;
			height: 88rpx;
			background-color: #1890FF;
			border-radius: 44rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			
			text {
				font-size: 32rpx;
				color: #fff;
				font-weight: bold;
			}
		}
		.custom-modal {
		  background: #fff;
		  padding: 30rpx;
		  border-radius: 20rpx;
		}
		.modal-title {
		  font-size: 34rpx;
		  font-weight: bold;
		  margin-bottom: 20rpx;
		}
		.modal-input {
		  width: 90%;
		  padding: 20rpx;
		  font-size: 28rpx;
		  border: 1px solid #ccc;
		  border-radius: 12rpx;
		}
		.checkbox-list {
		  display: flex;
		  flex-direction: column;
		  gap: 20rpx;
		}
		.checkbox-item {
		  display: flex;
		  align-items: center;
		  gap: 20rpx;
		}
		.other-input {
		  display: flex;
		  align-items: center;
		  gap: 20rpx;
		}
		.other-input input {
		  flex: 1;
		  border: 1px solid #ccc;
		  border-radius: 10rpx;
		  padding: 12rpx;
		}
		.modal-actions {
		  margin-top: 30rpx;
		  display: flex;
		  justify-content: space-between;
		}
		.modal-actions button {
		  flex: 1;
		  margin: 0 20rpx;
		  background-color: #007aff;
		  color: #fff;
		  border: none;
		  border-radius: 12rpx;
		  padding: 5rpx 0;
		}

	}
</style> 